<template>
  <div class="logininfor-management">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form
        ref="queryFormRef"
        :model="queryForm"
        :inline="true"
        label-width="80px"
      >
        <el-form-item label="登录地址" prop="ipaddr">
          <el-input
            v-model="queryForm.ipaddr"
            placeholder="请输入登录地址"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input
            v-model="queryForm.userName"
            placeholder="请输入用户名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryForm.status"
            placeholder="登录状态"
            clearable
            style="width: 200px"
          >
            <el-option label="成功" value="0" />
            <el-option label="失败" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="登录时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 280px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">
            搜索
          </el-button>
          <el-button icon="Refresh" @click="resetQuery">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card class="operation-card">
      <div class="operation-bar">
        <div class="left-operations">
          <el-button
            v-permission="['monitor:logininfor:remove']"
            type="danger"
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
          >
            删除
          </el-button>
          <el-button
            v-permission="['monitor:logininfor:remove']"
            type="warning"
            icon="Delete"
            @click="handleClean"
          >
            清空
          </el-button>
          <el-button
            v-permission="['monitor:logininfor:unlock']"
            type="primary"
            icon="Unlock"
            :disabled="single"
            @click="handleUnlock"
          >
            解锁
          </el-button>
          <el-button
            v-permission="['monitor:logininfor:export']"
            type="success"
            icon="Download"
            @click="handleExport"
          >
            导出
          </el-button>
        </div>
        <div class="right-operations">
          <el-tooltip content="刷新" placement="top">
            <el-button icon="Refresh" circle @click="getList" />
          </el-tooltip>
        </div>
      </div>

      <!-- 登录日志列表 -->
      <el-table
        v-loading="loading"
        :data="logininforList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="访问编号" prop="infoId" width="80" />
        <el-table-column
          label="用户名称"
          prop="userName"
          width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="登录地址"
          prop="ipaddr"
          width="130"
          show-overflow-tooltip
        />
        <el-table-column
          label="登录地点"
          prop="loginLocation"
          width="120"
          show-overflow-tooltip
        />
        <el-table-column label="浏览器" prop="browser" width="120" show-overflow-tooltip />
        <el-table-column label="操作系统" prop="os" width="120" show-overflow-tooltip />
        <el-table-column label="登录状态" prop="status" width="100">
          <template #default="{ row }">
            <dict-tag :options="statusOptions" :value="row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作信息" prop="msg" show-overflow-tooltip />
        <el-table-column
          label="登录日期"
          prop="loginTime"
          width="160"
          sortable="custom"
        >
          <template #default="{ row }">
            <span>{{ parseTime(row.loginTime) }}</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        v-model:page="queryForm.pageNum"
        v-model:limit="queryForm.pageSize"
        :total="total"
        @pagination="getList"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { 
  getLogininforList, 
  delLogininfor, 
  cleanLogininfor, 
  unlockLogininfor,
  exportLogininfor
} from '@/api/monitor/logininfor'
import { parseTime } from '@/utils/global'
import DictTag from '@/components/DictTag/index.vue'
import Pagination from '@/components/Pagination/index.vue'

// 遮罩层
const loading = ref(true)
// 选中数组
const ids = ref<number[]>([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 总条数
const total = ref(0)
// 登录日志表格数据
const logininforList = ref<any[]>([])
// 日期范围
const dateRange = ref<string[]>([])

// 表单引用
const queryFormRef = ref<FormInstance>()

// 状态数据字典
const statusOptions = ref([
  { label: '成功', value: '0', elTagType: 'success' },
  { label: '失败', value: '1', elTagType: 'danger' },
])

// 查询参数
const queryForm = reactive({
  pageNum: 1,
  pageSize: 10,
  ipaddr: '',
  userName: '',
  status: '',
  beginTime: undefined,
  endTime: undefined,
})

/** 查询登录日志 */
const getList = async () => {
  loading.value = true
  try {
    const params = {
      ...queryForm,
      beginTime: dateRange.value ? dateRange.value[0] : undefined,
      endTime: dateRange.value ? dateRange.value[1] : undefined,
    }
    const { data } = await getLogininforList(params)
    logininforList.value = data.rows
    total.value = data.total
  } catch (error) {
    console.error('获取登录日志失败:', error)
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryForm.pageNum = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = []
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.infoId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 删除按钮操作 */
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `是否确认删除访问编号为"${ids.value}"的数据项？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await delLogininfor(ids.value)
    await getList()
    ElMessage.success('删除成功')
  } catch (error) {
    console.log('取消删除')
  }
}

/** 清空按钮操作 */
const handleClean = async () => {
  try {
    await ElMessageBox.confirm('是否确认清空所有登录日志数据项？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    
    await cleanLogininfor()
    await getList()
    ElMessage.success('清空成功')
  } catch (error) {
    console.log('取消清空')
  }
}

/** 解锁按钮操作 */
const handleUnlock = async () => {
  const username = logininforList.value.find(item => 
    ids.value.includes(item.infoId)
  )?.userName
  
  try {
    await ElMessageBox.confirm(
      `是否确认解锁用户"${username}"数据项？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await unlockLogininfor(username)
    ElMessage.success('用户解锁成功')
  } catch (error) {
    console.log('取消解锁')
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    await ElMessageBox.confirm('是否确认导出所有登录日志数据项？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    
    const params = {
      ...queryForm,
      beginTime: dateRange.value ? dateRange.value[0] : undefined,
      endTime: dateRange.value ? dateRange.value[1] : undefined,
    }
    
    await exportLogininfor(params)
  } catch (error) {
    console.log('取消导出')
  }
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.logininfor-management {
  padding: 20px;
}

.search-card,
.operation-card {
  margin-bottom: 20px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.left-operations {
  display: flex;
  gap: 8px;
}

.right-operations {
  display: flex;
  gap: 8px;
}

:deep(.el-table) {
  .el-table__cell {
    padding: 8px 0;
  }
}
</style>

